ALTER PROC SP_CREATE_UPDATE_DIST_SO_DETAILS
(
	@DIST_SALESORDER_ID INT,
	@DIST_SALESORDER_NO VARCHAR(50),
	@CUSTOMER_PO 		VARCHAR(50),
	@DISTRIBUTOR_ID 	INT,
	@CUSTOMER_ID 		INT,
	@NEW_END_CUSTOMER_NAME VARCHAR(50),
	@SALESORDER_DATE 	DATETIME,
	@ACTUAL_SHIP_DATE 	DATETIME,
	@CREATED_BY 		VARCHAR(50),
	@STATUS				VARCHAR(50),
	@IS_CANCEL			INT,
	@OUT_DIST_SALESORDER_ID INT OUT
)
AS
BEGIN 
	DECLARE @NEW_END_CUST_ID INT

	SELECT @NEW_END_CUST_ID =CUSTOMER_ID FROM CUSTOMER WHERE C_NAME = @NEW_END_CUSTOMER_NAME
	IF @NEW_END_CUST_ID > 0 AND @CUSTOMER_ID < 0
	BEGIN
			SET @CUSTOMER_ID = @NEW_END_CUST_ID
	END
	IF @SALESORDER_DATE IS NULL OR @SALESORDER_DATE = ''
	BEGIN
		SET @SALESORDER_DATE = CONVERT( VARCHAR, GETDATE(), 101 )
	END	
	SELECT @OUT_DIST_SALESORDER_ID = DIST_SALESORDER_ID FROM DIST_SALES_ORDER WHERE DIST_SALESORDER_ID = @DIST_SALESORDER_ID
	IF( @@ROWCOUNT = 0 )
	BEGIN 
		
		INSERT INTO DIST_SALES_ORDER( DIST_SALESORDER_NO, CUSTOMER_PO, DISTRIBUTOR_ID, CUSTOMER_ID, SALESORDER_DATE, ACTUAL_SHIP_DATE, CREATED_BY , [TIMESTAMP], NEW_END_CUSTOMER_NAME, STATUS )
		VALUES ( @DIST_SALESORDER_NO, @CUSTOMER_PO, @DISTRIBUTOR_ID, @CUSTOMER_ID, @SALESORDER_DATE, CONVERT( VARCHAR, GETDATE(), 101 ), @CREATED_BY, CURRENT_TIMESTAMP, @NEW_END_CUSTOMER_NAME, 'OPEN' )	
		
		SELECT @OUT_DIST_SALESORDER_ID = @@IDENTITY
	END
	ELSE
	BEGIN
		UPDATE DIST_SALES_ORDER SET CUSTOMER_PO = @CUSTOMER_PO,
								CUSTOMER_ID = @CUSTOMER_ID,
							NEW_END_CUSTOMER_NAME=@NEW_END_CUSTOMER_NAME,
						[TIMESTAMP]	= CURRENT_TIMESTAMP, IS_CANCEL=@IS_CANCEL, STATUS= @STATUS
					WHERE DIST_SALESORDER_ID = @DIST_SALESORDER_ID
	END
END	
